<?php

namespace Verify;

use Verify\CheckException;
use Verify\Rules;

class Checker
{
    use Rules;

    /*
     * 输入
     */
    protected $_input = [];

    /*
     * 验证规则
     */
    protected $_rules = [];

    /*
     * 提示
     */
    protected $_msg = [];

    /*
     * 错误信息
     */
    public $_errors = [];

    /*
     * 实例
     */
    static protected $_validator;

    /*
     * 是否直接返回
     */
    protected $_direct = false;

    /*
     * 数据
     */
    public $_data = [];

    /*
     * 数据表
     */
    protected $_table = '';

    private function __construct()
    {

    }

    static public function getInstance()
    {
        if(self::$_validator instanceof self) {
            return self::$_validator;
        }
        self::$_validator = new self();
        return self::$_validator;
    }

    /*
     * 验证数据
     * @input
     * @rules
     * @msg
     */
    public function validate($input = [], $rules = [], $msg = [])
    {
        $this->_input = $input;
        $this->_rules = $rules;
        $this->_msg = $msg;
        if($this->_direct === true && ! empty($this->_errors)) {
            return $this;
        }
        $data = [];
        foreach($rules as $key => $val) {
            $rule_arr = explode('|', $val['rules']);

            foreach($rule_arr as $k => $v) {
                $params = explode(':', $v);
                $arg = $params[1] ? $params[1] : '';
                $func = $this->getFunc($params[0]);

                $result = call_user_func([$this, $func], $key, $arg);
                if($this->_direct && !$result) {
                    return $this;
                }
            }
            if($input[$key]) {
                $this->_data[$key] = $input[$key];  //将验证过后的数据保存下来
            }
        }
        return $this;
    }

    /*
     * 获取方法
     */
    public function getFunc($name)
    {
        $func = '';
        $funcs = explode('_', $name);
        $len = count($func_arr);
        if($len == 1) {
            $func = $name;
        } else {
            foreach($funcs as $key => $val) {
                if($key > 0) {
                    $func .= ucfirst($val);
                } else {
                    $func .= $val;
                }
            }
        }
        $methods = get_class_methods(Rules::class);
        if(! in_array($func, $methods)) {
            throw new CheckException('系统错误：验证方法不存在', 500);
        }
        return $func;
    }

    /*
     * 是否直接返回
     */
    public function direct($direct = true)
    {
        $this->_direct = $direct;
        return $this;
    }

    /*
     * 数据表
     */
    public function table($table)
    {
        $this->_table = $table;
        return $this;
    }

    /*
     * 获取错误信息
     */
    public function getErrors()
    {
        return $this->_errors;
    }
}